<template>
    <img v-lazy="image.src" :style="imgStyle" :alt="image.alt" /> 
</template>

<script type="text/javascript">
import Vue from 'vue'
import VueLazyload from 'vue-lazyload'
import smartMouse from "../plugin/smartMouse"

Vue.use(VueLazyload, {
    preLoad: 1.3,
    error: '/static/error.png',
    loading: '/static/loading.svg',
    attempt: 1
});

export default {
    mixins: [smartMouse],
    name: 'lazy-img',
    props: {
        'size': {
            type: Number,
            required: true
        },
        'image': {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            loaded: false,
        }
    },
    computed: {
        imgStyle() {
            var width, height, tx, ty;
            if (!this.loaded) {
                width = height = this.size * 0.5;
            } else {
                var rate = this.$el.naturalHeight / this.$el.naturalWidth;
                if (rate > 1) {
                    width = this.size;
                    height = Math.max(width * rate, this.size);
                } else {
                    height = this.size;
                    width = Math.max(height / rate, this.size);
                }
            }
            tx = (width - this.size) / 2;
            ty = (height - this.size) / 2;
            return {
                width: width + 'px',
                height: height + 'px',
                transform: `translate(${-tx}px, ${-ty}px)`
            }
                
        }
    },
    created() {
        var vm = this;
        var handler = function({el}) {
            if (el == vm.$el) {
                vm.$Lazyload.$off('loaded', handler);
                var loadedFn = function() {
                    window.requestAnimationFrame(function() {
                        vm.loaded = true;
                    });
                    vm.$el.removeEventListener('load', loadedFn);
                }
                vm.$el.addEventListener('load', loadedFn);

                // console.log('loaded', vm.$el);
            }
        };
        vm.$Lazyload.$on('loaded', handler);
    }
}

</script>

<style type="text/css" scoped>

</style>